//
//  BuyerRefundDetailVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/3/19.
//  Copyright © 2020 cat. All rights reserved.
//

#import "BuyerRefundDetailVC.h"
#import "BuyerRefundModel.h"
#import "BuyerRefundHeadView.h"
#import "PlatformInterventionVC.h"
#import "JCHATConversationViewController.h"

@interface BuyerRefundDetailVC (){
    UIScrollView *backScroll;
}
@property (nonatomic, strong)UIView *historyView;

@property(nonatomic, strong)BuyerRefundHeadView *headView;
@property(nonatomic, strong)BuyerRefundModel *model;

@property (nonatomic, strong)UIView *infoView;
@property (nonatomic, strong)UIImageView *orderImg;
@property (nonatomic, strong)UILabel *orderTitleLb;
@property (nonatomic, strong)UILabel *orderContentLb;
@property (nonatomic, strong)UILabel *orderPriceLb;
@property (nonatomic, strong)UILabel *orderCountLb;

@end

@implementation BuyerRefundDetailVC
#pragma mark------买家获取退款详情----------
-(void)requestGoodsOrderRefundInfo{    
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.orderId,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":self.orderId,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                            };
    
    [WYNetworking postWithUrl:@"Buyer.getGoodsOrderRefundInfo" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            NSDictionary *infos = [info firstObject];
            self.model = [BuyerRefundModel modelWithDictionary:infos];
            
            [backScroll addSubview:self.headView];
            [backScroll addSubview:self.historyView];
            [backScroll addSubview:self.infoView];

            backScroll.contentSize = CGSizeMake(_window_width, self.headView.height+self.historyView.height+self.infoView.height);

        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
        }];

}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = YZMsg(@"退款详情");
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    backScroll = [[UIScrollView alloc]init];
    backScroll.frame = CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight);
    backScroll.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:backScroll];

    [self requestGoodsOrderRefundInfo];
    
    
}
-(BuyerRefundHeadView *)headView{
    YBWeakSelf;
    if (!_headView) {
        _headView = [[BuyerRefundHeadView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 120)];
        [_headView setRefundData:self.model];
        _headView.clickEvent = ^(NSString * _Nonnull btnTitle) {
            if ([btnTitle isEqual:YZMsg(@"取消申请")]) {
                [weakSelf cancelRefundGoodsOrder];
            }else if ([btnTitle isEqual:YZMsg(@"重新申请")]){
                [weakSelf reapplyRefundGoodsOrder];
            }else if ([btnTitle isEqual:YZMsg(@"平台介入")]){
                [weakSelf applyPlatformInterpose];
            }
        };
    }
    return _headView;
}
-(UIView *)historyView{
    if (!_historyView) {
        _historyView = [[UIView alloc]init];
        _historyView.backgroundColor = UIColor.whiteColor;
        _historyView.frame = CGRectMake(0, _headView.bottom+5, _window_width, 50);
        [backScroll addSubview:_historyView];
        UILabel *titlelb = [[UILabel alloc]init];
        titlelb.frame  = CGRectMake(12, 50/2-10, 180, 20);
        titlelb.text = YZMsg(@"协商历史");
        titlelb.font = [UIFont systemFontOfSize:14];
        titlelb.textColor = [UIColor blackColor];
        [_historyView addSubview:titlelb];
        
        UIImageView *rightImg = [[UIImageView alloc]init];
        rightImg.frame =CGRectMake(_window_width-30, 50/2-8, 16, 16);
        rightImg.image = [UIImage imageNamed:@"shop_right"];
        [_historyView addSubview:rightImg];
        
        UIButton *historyBtn = [UIButton buttonWithType:0];
        historyBtn.frame = CGRectMake(0, 0, _historyView.width, _historyView.height);
        [historyBtn addTarget:self action:@selector(historyRefundClick) forControlEvents:UIControlEventTouchUpInside];
        [_historyView addSubview:historyBtn];

    }
    return _historyView;
}

-(UIView *)infoView{
    if (!_infoView) {
        _infoView = [[UIView alloc]initWithFrame:CGRectMake(0, _historyView.bottom+5, _window_width, 450)];
        _infoView.backgroundColor = UIColor.whiteColor;
        
        UILabel *lb = [[UILabel alloc]initWithFrame:CGRectMake(12, 10, 80, 20)];
        lb.text = YZMsg(@"退款信息");
        lb.font = [UIFont systemFontOfSize:14];
        lb.textColor = [UIColor blackColor];
        [_infoView addSubview:lb];
        
        _orderImg = [[UIImageView alloc]init];
        _orderImg.frame = CGRectMake(12, lb.bottom+5, 90, 90);
        _orderImg.backgroundColor = [UIColor lightGrayColor];
        _orderImg.layer.cornerRadius = 5;
        _orderImg.layer.masksToBounds = YES;
        [_orderImg sd_setImageWithURL:[NSURL URLWithString:self.model.spec_thumb_format]];
        [_infoView addSubview:_orderImg];
        
        _orderTitleLb = [[UILabel alloc]init];
        _orderTitleLb.textColor = [UIColor blackColor];
        _orderTitleLb.font = [UIFont systemFontOfSize:14];
        _orderTitleLb.text = self.model.goods_name;
        [_infoView addSubview:_orderTitleLb];
        [_orderTitleLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_orderImg.mas_right).offset(5);
            make.top.equalTo(_orderImg).offset(8);
            make.height.mas_equalTo(18);
        }];
        
        _orderPriceLb = [[UILabel alloc]init];
        _orderPriceLb.textColor = [UIColor blackColor];
        _orderPriceLb.font = [UIFont systemFontOfSize:14];
        _orderPriceLb.text =[NSString stringWithFormat:@"%@%@",YZMsg(@"¥"), self.model.price];
        _orderPriceLb.textAlignment = NSTextAlignmentRight;
        [_infoView addSubview:_orderPriceLb];
        [_orderPriceLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_infoView).offset(-10);
            make.centerY.height.equalTo(_orderTitleLb);
        }];
        _orderContentLb = [[UILabel alloc]init];
        _orderContentLb.textColor =Normal_TextColor;
        _orderContentLb.font = [UIFont systemFontOfSize:14];
        _orderContentLb.text =self.model.spec_name;// @"麻辣鲜香味";
        [_infoView addSubview:_orderContentLb];
        [_orderContentLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_orderTitleLb);
            make.top.equalTo(_orderTitleLb.mas_bottom).offset(5);
            make.height.equalTo(_orderTitleLb);
        }];
        
        _orderCountLb = [[UILabel alloc]init];
        _orderCountLb.textColor = Normal_TextColor;
        _orderCountLb.font = [UIFont systemFontOfSize:14];
        _orderCountLb.text =[NSString stringWithFormat:@"x%@",self.model.nums];// @"x1";
        _orderCountLb.textAlignment = NSTextAlignmentRight;
        [_infoView addSubview:_orderCountLb];
        [_orderCountLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_infoView).offset(-10);
            make.centerY.height.equalTo(_orderContentLb);
        }];

        
        [PublicObj lineViewWithFrame:CGRectMake(0, _orderImg.bottom+5, _window_width, 5) andColor:RGB(245, 245, 245) andView:_infoView];
        
        NSArray *arr;
        if ([self.model.refund_shop_result isEqual:@"-1"] && [self.model.is_platform_interpose isEqual:@"0"]) {
            arr= @[YZMsg(@"退款方式:"),YZMsg(@"退款金额:"),YZMsg(@"退款原因:"),YZMsg(@"申请时间:"),YZMsg(@"问题描述:"),YZMsg(@"拒绝原因:"),YZMsg(@"拒绝描述:")];
        }else{
            arr= @[YZMsg(@"退款方式:"),YZMsg(@"退款金额:"),YZMsg(@"退款原因:"),YZMsg(@"申请时间:"),YZMsg(@"问题描述:")];
        }
        for (int i = 0;i < arr.count ; i++) {
            UILabel *lb = [[UILabel alloc]init];
            lb.font = [UIFont systemFontOfSize:14];
            lb.textColor = Normal_TextColor;
            lb.text = arr[i];
            [_infoView addSubview:lb];
            if (i == 4) {
                CGFloat textHeight = [PublicObj heightOfString:self.model.refund_content andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];
                if (self.model.refund_content.length > 0) {
                    [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(_infoView).offset(12);
//                        make.top.equalTo(_orderImg.mas_bottom).offset((i-1)*30+textHeight);
                        make.top.equalTo(_orderImg.mas_bottom).offset(15+i*30);

                        make.height.mas_equalTo(20);
                    }];

                }else{
                    [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.equalTo(_infoView).offset(12);
                        make.top.equalTo(_orderImg.mas_bottom).offset(15+i*30);
                        make.height.mas_equalTo(20);
                    }];

                }

            }else if(i == 5){
                CGFloat textHeight = [PublicObj heightOfString:self.model.refund_content andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];

                [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_infoView).offset(12);
                    make.top.equalTo(_orderImg.mas_bottom).offset(15+i*30+textHeight);
                    make.height.mas_equalTo(20);
                }];

            } else if(i == 6){
                CGFloat descHeight = [PublicObj heightOfString:self.model.shop_handle_desc andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];
                [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_infoView).offset(12);
                    make.top.equalTo(_orderImg.mas_bottom).offset(15+i*30+descHeight);
                    make.height.mas_equalTo(20);
                }];

            }else{
                [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_infoView).offset(12);
                    make.top.equalTo(_orderImg.mas_bottom).offset(15+i*30);
                    make.height.mas_equalTo(20);
                }];

            }
            
            
            UILabel *infoLb = [[UILabel alloc]init];
            infoLb.font = [UIFont systemFontOfSize:14];
            if (i < 2) {
                infoLb.textColor = Pink_Cor;
            }else if(i > 4){
                lb.textColor =RGB(239, 224, 49);// [UIColor redColor];
                infoLb.textColor =RGB(239, 224, 49);// [UIColor redColor];
            }else{
                infoLb.textColor = [UIColor grayColor];
            }
            [_infoView addSubview:infoLb];
            if (i == 4 || i == 6) {
                [infoLb mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(lb.mas_right).offset(5);
                    make.top.equalTo(lb.mas_top);
                    make.width.mas_equalTo(_window_width-100);
                }];

            }else{
                [infoLb mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(lb.mas_right).offset(5);
                    make.centerY.equalTo(lb.mas_centerY);
                    make.height.equalTo(lb);
                }];

            }
            
            switch (i) {
                case 0:{
                    //（退款类型 0 仅退款 1 退货退款）
                    NSString *typeStr;
                    if ([self.model.type isEqual:@"0"]) {
                        typeStr =YZMsg(@"仅退款");
                    }else{
                        typeStr =YZMsg(@"退货退款");

                    }
                    infoLb.text = typeStr;
                }
                    break;
                case 1:
                    infoLb.text =[NSString stringWithFormat:@"¥%@", self.model.total];
                    break;
                case 2:
                    infoLb.text = self.model.refund_reason;
                    break;
                case 3:
                    infoLb.text = self.model.addtime;
                    break;
                case 4:
                    infoLb.text = self.model.refund_content;
                    infoLb.lineBreakMode = NSLineBreakByWordWrapping;
                    infoLb.numberOfLines = 0;
                    CGFloat textHeight = [PublicObj heightOfString:self.model.refund_content andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];
                    infoLb.size = CGSizeMake(_window_width-100, textHeight);
                    _infoView.size = CGSizeMake(_window_width, 450+textHeight);

                    [_infoView layoutIfNeeded];
                    break;
                case 5:
                    infoLb.text = self.model.shop_refuse_reason;
                    break;
                case 6:
                    infoLb.text = self.model.shop_handle_desc;
                    infoLb.lineBreakMode = NSLineBreakByWordWrapping;
                    infoLb.numberOfLines = 0;
                    CGFloat descHeight = [PublicObj heightOfString:self.model.shop_handle_desc andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];
                    infoLb.size = CGSizeMake(_window_width-100, descHeight);
                    [_infoView layoutIfNeeded];

                    break;
                default:
                    break;
            }
        }
        CGFloat textHeight = [PublicObj heightOfString:self.model.refund_content andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];
        CGFloat descHeight = [PublicObj heightOfString:self.model.shop_handle_desc andFont:[UIFont systemFontOfSize:14] andWidth:_window_width-100];
        _infoView.size = CGSizeMake(_window_width, 450+descHeight+textHeight);

        [PublicObj lineViewWithFrame:CGRectMake(0, (_orderImg.bottom+25)+arr.count*30+textHeight+descHeight, _window_width, 1) andColor:RGB(245, 245, 245) andView:_infoView];


        UIButton *kefuBtn = [UIButton buttonWithType:0];
        [kefuBtn setBackgroundColor: UIColor.whiteColor];
        [kefuBtn setImage:[UIImage imageNamed:@"联系客服"] forState:0];
        [kefuBtn setTitle:YZMsg(@"联系客服") forState:0];
        [kefuBtn setTitleColor:[UIColor blackColor] forState:0];
        kefuBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [kefuBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0 )];
        [kefuBtn addTarget:self action:@selector(kefuBtnClick) forControlEvents:UIControlEventTouchUpInside];

        [_infoView addSubview:kefuBtn];
        [kefuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_infoView);
            make.top.equalTo(_orderImg.mas_bottom).offset(30+arr.count*30+textHeight+descHeight);
            make.width.equalTo(_infoView).multipliedBy(0.5);
            make.height.mas_equalTo(40);
        }];
        
        UIButton *callBtn = [UIButton buttonWithType:0];
        [callBtn setBackgroundColor: UIColor.whiteColor];
        [callBtn setImage:[UIImage imageNamed:@"拨打电话"] forState:0];
        [callBtn setTitle:YZMsg(@"拨打电话") forState:0];
        [callBtn setTitleColor:[UIColor blackColor] forState:0];
        callBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [callBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0 )];
        [callBtn addTarget:self action:@selector(callBtnClick) forControlEvents:UIControlEventTouchUpInside];

        [_infoView addSubview:callBtn];
        
        [callBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(kefuBtn.mas_right);
            make.top.equalTo(kefuBtn);
            make.width.equalTo(_infoView).multipliedBy(0.5);
            make.height.mas_equalTo(40);
        }];
        
        [PublicObj lineViewWithFrame:CGRectMake(_window_width/2, (_orderImg.bottom+25)+arr.count*30+textHeight+descHeight, 1, 50) andColor:RGB(245, 245, 245) andView:_infoView];


    }
    return _infoView;
}

//买家取消退款申请
-(void)cancelRefundGoodsOrder{
    UIAlertController *cancelAlert = [UIAlertController alertControllerWithTitle:YZMsg(@"取消退款申请后，该订单无法再次申请退款,确定取消?") message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.orderId,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
        NSString *sign = [PublicObj sortString:signdic];

        NSDictionary *dic = @{
                              @"uid":[Config getOwnID],
                              @"token":[Config getOwnToken],
                              @"orderid":self.orderId,
                              @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                              @"sign":sign
                                };
        
        [WYNetworking postWithUrl:@"Buyer.cancelRefundGoodsOrder" Dic:dic Suc:^(int code, id info, NSString *msg) {
            if (code ==0) {
                [MBProgressHUD showError:msg];
                [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
            }else{
                [MBProgressHUD showError:msg];
            }

            } Fail:^(id fail) {
                
            }];

    }];
    UIAlertAction *cacel = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];
    [sure setValue:Normal_Color forKey:@"_titleTextColor"];
    [cacel setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
    [cancelAlert addAction:sure];
    [cancelAlert addAction:cacel];
    
    
    [self presentViewController:cancelAlert animated:YES completion:nil];
    
}
//重新申请
-(void)reapplyRefundGoodsOrder{
    NSString *url = [purl stringByAppendingFormat:@"?service="];
    
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"orderid":self.orderId,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":self.orderId,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                            };
    
    [WYNetworking postWithUrl:@"Buyer.reapplyRefundGoodsOrder" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:msg];
            [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
        }];

}
//平台介入
-(void)applyPlatformInterpose{
    YBWeakSelf;
    PlatformInterventionVC *platform = [[PlatformInterventionVC alloc]init];
    platform.orderIDStr = self.orderId;
    platform.reloadEvent = ^{
        [weakSelf requestGoodsOrderRefundInfo];
    };
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:platform animated:YES];
}
//查看协商历史
-(void)historyRefundClick{
    PubH5 *h5VC = [[PubH5 alloc]init];
    NSString *url =[NSString stringWithFormat:@"%@/appapi/goodsorderrefund/index",h5url];
    h5VC.url = [self addurl:url];
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:h5VC animated:YES];
}
//所有h5需要拼接uid和token
-(NSString *)addurl:(NSString *)url{
    return [url stringByAppendingFormat:@"&uid=%@&token=%@&orderid=%@&user_type=buyer",[Config getOwnID],[Config getOwnToken],self.orderId];
}
//联系买家
-(void)kefuBtnClick{
    if ([self.model.service_uid isEqual:@"1"]) {
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:nil message:YZMsg(@"请到个性设置-关于我们中联系客服") preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [sureAction setValue:Normal_Color forKey:@"_titleTextColor"];
        [alertControl addAction:sureAction];
        [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:alertControl animated:YES completion:nil];

    }else{
        //创建会话
        NSDictionary *userDic = @{
            @"id":self.model.service_uid,
            @"user_nickname":self.model.service_name,
            @"avatar":self.model.service_avatar,
        };
        [[YBMessageManager shareManager] chatWithUser:userDic];
    }
}
-(void)callBtnClick{
    NSString *phone =[NSString stringWithFormat:@"tel://%@",self.model.service_phone] ;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];

}

@end
